package com.wzy.java;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName：ReplaceEmailTemplate
 * @Description：邮件模板转换工具
 * @Author：chenyb
 * @Date：2020/11/30 6:52 下午
 * @Versiion：1.0
 */
public class ReplaceEmailTemplate {
    /**
     * 实体类转Map
     *
     * @param clazz 类
     * @param obj   实体类
     * @param <T>   实体类
     * @return
     */
    public static <T> Map<String, Object> replaceContext(Class<?> clazz, T obj) {
        Map<String, Object> map = new HashMap<String, Object>();
        Field[] declaredFields = clazz.getDeclaredFields();
        for (Field f : declaredFields) {
            try {
                //打开可见性，要不然获取不到值
                f.setAccessible(true);
                map.put(f.getName(), f.get(obj));
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } finally {
                //关闭可见性
                f.setAccessible(false);
            }
        }
        return map;
    }

    public static void main(String[] args) {
        User user = new User(1,"wzy",23,1);
        Map<String, Object> map = ReplaceEmailTemplate.replaceContext(User.class,user);
        System.out.println(map);
    }
}